package com.qf.web;

import com.github.pagehelper.PageInfo;
import com.qf.bean.Dept;
import com.qf.bean.Employee;
import com.qf.bean.Role;
import com.qf.service.DeptService;
import com.qf.service.EmployeeService;
import com.qf.service.RoleService;
import com.qf.util.Enume1.EmployeeEnum;
import com.qf.util.Enume1.PageEnum;
import com.qf.util.ExceIUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    //批量删除
    @RequestMapping("/resource/demo2/deletebyids")
    public void deletes(int[] empid,HttpServletResponse response,String method){

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            if(method.equals("delete")){
                int i = employeeService.deletes(empid);
                if(i>0){
                    writer.print("<script>alert('删除成功');location.href='/resource/demo2/getusers'</script>");
                }else{
                    writer.print("<script>alert('删除失败');location.href='/resource/demo2/getusers'</script>");
                }
            }else if(method.equals("daochu")){
                try {
                    //导出数据
                    //1.查询被选中的数据信息
                    List<Employee> employeeList = employeeService.findbyids(empid);
                    //2.导出数据
                    ExceIUtils.createFirst("用户信息");
                    ExceIUtils.createOthers(employeeList);
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
                    ExceIUtils.export(new FileOutputStream("D://"+(format.format(new Date()))+".xls"));
                    writer.print("<script>alert('导出成功');location.href='/resource/demo2/getusers'</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    // 删除用户
    @RequestMapping("/resource/demo2/deletebyid")
    public void delect(int uid, HttpServletResponse response){
        //删除的方式1假删除2真删除
        //1表示未删除0表示已删除
        int i = employeeService.deleteByPrimaryKey(uid,EmployeeEnum.DELETE.getIsline());
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            if (i>0){
                writer.print("<script>alert('删除成功');location.href='/resource/demo2/getusers'</script>");
            }else{
                writer.print("<script>alert('删除失败');location.href='/resource/demo2/getusers'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改
    @RequestMapping("/resource/demo2/updateEmp")
    public String update(Employee employee){
        int i = employeeService.updateByPrimaryKeySelective(employee);
        if (i>0){
            return "redirect:/resource/demo2/getusers";
        }
        return "redirect:/resource/demo2/findbyid?uid="+employee.getId();
    }


    //主键查询
    @RequestMapping("/resource/demo2/findbyid")
    public String findbyid(int uid,ModelMap map){
        //得到用户的信息
        Employee employee = employeeService.selectByPrimaryKey(uid);
        map.addAttribute("emp",employee);
        //查询所有的部门信息
        List<Dept> depts = deptService.findalldepts();
        map.addAttribute("depts",depts);
        //根据用户的部门信息查询对应的职位信息
        List<Role> roles = roleService.findbyDeptid(employee.getDeptid());
        map.addAttribute("roles",roles);

        return "/resource/demo2/update";
    }




    //新增用户
    @RequestMapping("/resource/demo2/insertEmp")
    public String insert(Employee employee){
        employee.setCreatedate(new Date());
        employee.setState(1);//1表示未删除 0表示以删除
        int insert = employeeService.insert(employee);
        if (insert>0){
                return "redirect:/resource/demo2/getusers";
        }
                return "redirect:/resource/demo2/getalldepts";
        }


    //用户管理模块查询列表 index表示页码值
    @RequestMapping("resource/demo2/getusers")
    @RequiresPermissions("user:selectall")//访问该请求的权限code
    public String getall(@RequestParam(defaultValue = "1") int index,
                         ModelMap map,String username,String rolename,String daptname){
        PageInfo<Employee> pageInfo = employeeService.getall(index, PageEnum.pagesize.getSize(),username,rolename,daptname);
        map.addAttribute("pi",pageInfo);
        //存储模糊条件到页面
        map.addAttribute("uname",username);
        map.addAttribute("rname",rolename);
        map.addAttribute("dname",daptname);
        return "resource/demo2/list";
    }

//    //登录
//    @RequestMapping("/login")
//    public String login(String username, String password, HttpSession session){
//        Employee employee = employeeService.login(username, password);
//        if(employee==null){
//            return "login";
//        }
//        //将登录成功的信息保存在session中
//        session.setAttribute("user",employee);
//        return "redirect:/index.jsp";
//    }
    //处理登陆时，异常情况问题
    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws Exception{
        //得到异常信息 shiroLoginFailure是shiro认证失败的时候，存的key值
        String shiroLoginFailure = (String)request.getAttribute("shiroLoginFailure");
        if (shiroLoginFailure!=null){
            //判断是那个类型的异常
            if (UnknownAccountException.class.getName().equals(shiroLoginFailure)){
                throw  new Exception("账户错误");
            }else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)){
                throw  new Exception("密码错误");
            }else {
                throw  new Exception("未知错误");
            }
        }


        return "login";
    }


//
//    //退出
//    @RequestMapping("/loginout")
//    public String loginout(HttpSession session){
//        //清除session
//        session.invalidate();
//        return "redirect:/login.jsp";
//    }

}

